package org.wattdepot.cli;

import java.text.DecimalFormat;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.resource.source.jaxb.Source;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Computes the carbon content of the source.
 * Takes the total carbon generated for the hour divided by the 
 * total energy generated for the hour
 * Input 1: carboncontent SIM_IPP 2009-11-15T12:00:00.000-10:00 sampling-interval 10
 * Input 2: carboncontent SIM_KAHE 2009-11-15T12:00:00.000-10:00 sampling-interval 10
 * @author Edwin Lim, Wing Ma Cheung
 *
 */
public class CarbonContent extends CommandLineInterface implements WattDepotCliCommand {
  /**
   * Calls the method that would print the summarized list of a single power plant.
   * @param args Strings of input arguments
   * @return output a collection of information about one source
   */
  @Override
  public String doCommand(List<String> args) {
    String input = args.get(0);
    String timeStamp = args.get(1);
    String interval = args.get(3);
    double total = 0.0;
    double carbonGenerated = 0.0;
    double energyGenerated = 0.0;
    String output = "";
    Source source = null;
    // checks that the source is valid
    try {
      source = searchSource(input);
    }
    catch (WattDepotClientException eCli) {
      eCli.printStackTrace();
    }
    
    if (source == null) {
      return sourceNotFound;
    }
    XMLGregorianCalendar startTime = null;
    try {
      startTime = Tstamp.makeTimestamp(timeStamp);
    }
    catch (Exception e) {
      System.out.println("should never happen.");
    }
    XMLGregorianCalendar endTime = Tstamp.incrementHours(startTime, 1);
    Integer intervalInt = Integer.parseInt(interval);
    try {
     carbonGenerated = client.getCarbonEmitted(source.getName(), startTime, endTime, intervalInt);
     energyGenerated = client.getEnergyGenerated(source.getName(), startTime, endTime, intervalInt);
    }
    catch (WattDepotClientException eCli) {
      eCli.printStackTrace();
    }
    // convert the output into a two decimal places
    DecimalFormat df = new DecimalFormat("#.##");
    // calculates the carbon content in MWh.
    total = (carbonGenerated / energyGenerated) * 1000000.0;

    output = Double.toString(total);
    output = df.format(total);
    return output + " lbs CO2/MWh";
  }
    
}
